import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression

# 样本数据
x = np.array([1, 2, 3])
y = np.array([2, 3, 4])

# 判别模型 - 线性回归
reg = LinearRegression().fit(x.reshape(-1, 1), y)
beta_0, beta_1 = reg.intercept_, reg.coef_[0]

# 生成模型 - 拟合 x = phi_0 + phi_1 * y
A = np.vstack([np.ones(len(y)), y]).T
phi_1, phi_0 = np.linalg.lstsq(A, x, rcond=None)[0]

# 打印结果
print(f"判别模型: y = {beta_0} + {beta_1} * x")
print(f"生成模型: x = {phi_0} + {phi_1} * y")

# 预测
y_pred_discriminative = beta_0 + beta_1 * x
x_pred_generative = phi_0 + phi_1 * y

print(f"判别模型预测的 y: {y_pred_discriminative}")
print(f"生成模型预测的 x: {x_pred_generative}")

# 绘图
plt.scatter(x, y, color='black', label='Data points')
plt.plot(x, y_pred_discriminative, color='blue', label='Discriminative Model')
plt.plot(x_pred_generative, y, color='red', linestyle='dashed', label='Generative Model')
plt.legend()
plt.show()
